#include<iostream>
#include<cstdio>
#include<pthread.h>
#include<string>
#include<functional>

using namespace std;

namespace zzx
{
    template<typename T>
    using fun_c = function<void(T)>;

    template<typename T>
    class thread
    {
      public:
        thread(fun_c<T> func, T data, const string& name = "thread none-name")  
            :_func(func), _data(data), _name(name),_stop(true)
            { }
        
        ~thread(){ }

        //注意：类成员函数,默认第一个参数为this指针,静态成员函数无this指针
        static void* threadroutine(void* args) 
        {
            thread<T>* td = static_cast<thread<T>*>(args); //强制类型转换
            td->_func(td->_data);
            return nullptr;
        }

        bool start()
        {
            //为了在静态成员函数threadroutine中访问成员变量,参数传递类对象指针(this)
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if(n != 0) return false;
            _stop = false;
            return true;
        }

        void detach()
        {
            if(!_stop)
                pthread_detach(_tid);
        }

        void join()
        {
            if(!_stop)
                pthread_join(_tid, nullptr);
        }

        string name()
        {
            return _name;
        }

        void stop()
        {
            _stop = true;
        }

      private:
        pthread_t _tid;
        string _name;
        T _data;
        fun_c<T> _func;
        bool _stop;
    };
}